package com.cpx.service.impl;

import com.cpx.dto.PageBeanDto;
import com.cpx.mapper.GoodsBrandMapper;
import com.cpx.mapper.GoodsCategoryMapper;
import com.cpx.mapper.GoodsMapper;
import com.cpx.mapper.GoodsSupplierMapper;
import com.cpx.po.Goods;
import com.cpx.po.GoodsBrand;
import com.cpx.po.GoodsCategory;
import com.cpx.po.GoodsSupplier;
import com.cpx.service.GoodsService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.ss.usermodel.VerticalAlignment;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import tk.mybatis.mapper.entity.Example;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * @Auther: PanBin
 * @Date: 2018-11-13 17:15
 * @Description:
 * @Version: 1.0
 */
@RestController
public class GoodsServiceImpl extends BaseServiceImpl<Goods> implements GoodsService {

    @Autowired
    private GoodsMapper goodsMapper;
    @Autowired
    private GoodsCategoryMapper goodsCategoryMapper;
    @Autowired
    private GoodsBrandMapper goodsBrandMapper;
    @Autowired
    private GoodsSupplierMapper goodsSupplierMapper;

    @Override
    public List<GoodsCategory> getCategoryTree(@RequestBody GoodsCategory goodsCategory) {
        List<GoodsCategory> goodsCategoryList = goodsCategoryMapper.selectAll();
        return goodsCategoryList;
    }

    @Override
    public int updateCategoryNode(@RequestBody GoodsCategory goodsCategory, Integer type) {
        if (type.intValue() < 2) {
            goodsCategory.setId(null);
            goodsCategory.setCreateDate(new Date());
            goodsCategoryMapper.insertUseGeneratedKeys(goodsCategory);
            return goodsCategory.getId();
        } else if (type.intValue() < 3) {
            goodsCategoryMapper.updateByPrimaryKeySelective(goodsCategory);
        } else {
            Example example = new Example(GoodsCategory.class);
            Integer id = goodsCategory.getId();
            Example.Criteria criteria = example.createCriteria().andEqualTo("id",id);;
            example.or().andEqualTo("parentId",id);
            goodsCategoryMapper.deleteByExample(example);
        }
        return 0;
    }

    @Override
    public PageBeanDto<GoodsBrand> selectBrandPage(@RequestBody GoodsBrand goodsBrand, @RequestParam("pageSize") Integer pageSize, @RequestParam("pageNum") Integer pageNum) {
        PageHelper.startPage(pageNum,pageSize);
        Example example = new Example(GoodsBrand.class);
        String brandName = goodsBrand.getBrandName();
        if (brandName != null && !brandName.isEmpty()) {
            example.createCriteria().andLike("brandName", "%" + goodsBrand.getBrandName() + "%");
        }
        List<GoodsBrand> goodsBrandList = goodsBrandMapper.selectByExample(example);
        PageInfo<GoodsBrand> pageInfo = new PageInfo<>(goodsBrandList);
        PageBeanDto<GoodsBrand> pageBeanDto = new PageBeanDto<>();
        pageBeanDto.setPageList(goodsBrandList);
        pageBeanDto.setPageNum(pageNum);
        pageBeanDto.setTotalRow(pageInfo.getTotal());
        pageBeanDto.setTotalPage(pageInfo.getPages());
        return pageBeanDto;
    }

    @Override
    public int addBrand(@RequestBody GoodsBrand goodsBrand) {
        goodsBrand.setCreateDate(new Date());
        return goodsBrandMapper.insertSelective(goodsBrand);
    }

    @Override
    public int delBrand(@RequestParam("brandIds") Integer[] brandIds) {
        Example example = new Example(GoodsBrand.class);
        example.createCriteria().andIn("id",Arrays.asList(brandIds));
        return goodsBrandMapper.deleteByExample(example);
    }

    @Override
    public int editBrand(@RequestBody GoodsBrand goodsBrand) {
        return goodsBrandMapper.updateByPrimaryKeySelective(goodsBrand);
    }

    @Override
    public void exportBrand(@RequestBody GoodsBrand goodsBrand,HttpServletResponse response) throws Exception {
        //创建一个工作簿
        HSSFWorkbook workbook = new HSSFWorkbook();
        //创建一个工作表
        HSSFSheet sheet = workbook.createSheet("品牌表");
        sheet.setDefaultRowHeightInPoints(16);//设置默认宽高
        // 第四步，创建单元格，并设置值表头 设置表头居中
        HSSFCellStyle styleTitle = workbook.createCellStyle();
        styleTitle.setAlignment(HorizontalAlignment.CENTER); // 创建一个居中格式
        styleTitle.setVerticalAlignment(VerticalAlignment.CENTER);//垂直居中
        HSSFFont fontTitle = workbook.createFont();
        fontTitle.setBold(true);
        fontTitle.setFontHeightInPoints((short) 11);
        styleTitle.setFont(fontTitle);
        //设置表头
        HSSFRow rowHead = sheet.createRow(0);
        //创建单元格
        String[] heads = {"品牌编码","品牌名称","备注","创建时间"};
        //设置每个单元格的宽
        int[] cellWidth = {256 * 10 + 184,256 * 15 + 184,256 * 30 + 184,256 * 22 + 184};
        for (int i = 0; i < heads.length; i++) {
            //创建单元格
            HSSFCell cellHead = rowHead.createCell(i);
            cellHead.setCellValue(heads[i]);
            cellHead.setCellStyle(styleTitle);
            //设置单元格的宽
            sheet.setColumnWidth(i, cellWidth[i]);
        }
        Example example = new Example(GoodsBrand.class);
        String brandName = goodsBrand.getBrandName();
        if (brandName != null && !brandName.isEmpty()) {
            example.createCriteria().andLike("brandName","%" + brandName + "%");
        }
        //查询出所有的数据
        List<GoodsBrand> list = goodsBrandMapper.selectByExample(example);
        if (list.size() > 0) {
            HSSFCellStyle styleContent = workbook.createCellStyle();
            styleContent.setAlignment(HorizontalAlignment.CENTER); // 创建一个居中格式
            styleContent.setVerticalAlignment(VerticalAlignment.CENTER); // 创建一个垂直居中
            //创建字体,设置字体样式
            HSSFFont fontContent = workbook.createFont();
            fontContent.setFontHeightInPoints((short) 11);
            styleContent.setFont(fontContent);
            final DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            int i =1;
            for (GoodsBrand gb : list) {
                //写出数据到excel表
                //创建行
                HSSFRow row = sheet.createRow(i);
                row.setRowStyle(styleContent);
                //设置单元格的数据
                HSSFCell cell1 = row.createCell(0);
                cell1.setCellValue(gb.getId());
                cell1.setCellStyle(styleContent);
                HSSFCell cell2 = row.createCell(1);
                cell2.setCellValue(gb.getBrandName());
                cell2.setCellStyle(styleContent);
                HSSFCell cell3= row.createCell(2);
                cell3.setCellValue(gb.getRemark());
                cell3.setCellStyle(styleContent);

                //先创建出单元格
                HSSFCell cell4 = row.createCell(3);
                //先设置样式,在赋值
                cell4.setCellValue(df.format(gb.getCreateDate()));
                cell4.setCellStyle(styleContent);
                i ++;
            }
            ServletOutputStream os = response.getOutputStream();
            try {
                workbook.write(os);
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                //释放资源
                try {
                    os.close();
                    //关闭工作簿
                    workbook.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    @Override
    public PageBeanDto<GoodsSupplier> selectSupplierPage(@RequestBody GoodsSupplier goodsSupplier, @RequestParam("pageSize") Integer pageSize, @RequestParam("pageNum") Integer pageNum) {
        PageHelper.startPage(pageNum,pageSize);
        Example example = new Example(GoodsSupplier.class);
        String supplierName = goodsSupplier.getSupplierName();
        if (supplierName != null && !supplierName.isEmpty()) {
            example.createCriteria().andLike("supplierName", "%" + supplierName + "%");
        }
        List<GoodsSupplier> goodsSupplierList = goodsSupplierMapper.selectByExample(example);
        PageInfo<GoodsSupplier> pageInfo = new PageInfo<>(goodsSupplierList);
        PageBeanDto<GoodsSupplier> pageBeanDto = new PageBeanDto<>();
        pageBeanDto.setPageList(goodsSupplierList);
        pageBeanDto.setPageNum(pageNum);
        pageBeanDto.setTotalRow(pageInfo.getTotal());
        pageBeanDto.setTotalPage(pageInfo.getPages());
        return pageBeanDto;
    }

    @Override
    public int addSupplier(@RequestBody GoodsSupplier goodsSupplier) {
        goodsSupplier.setCreateDate(new Date());
        return goodsSupplierMapper.insertSelective(goodsSupplier);
    }

    @Override
    public int editSupplier(@RequestBody GoodsSupplier goodsSupplier) {
        return goodsSupplierMapper.updateByPrimaryKeySelective(goodsSupplier);
    }

    @Override
    public int delSupplier(@RequestParam("supplierIds") Integer[] supplierIds) {
        Example example = new Example(GoodsSupplier.class);
        example.createCriteria().andIn("id",Arrays.asList(supplierIds));
        return goodsSupplierMapper.deleteByExample(example);
    }

    @Override
    public void exportSupplier(@RequestBody GoodsSupplier goodsSupplier,HttpServletResponse response) throws Exception {
        //创建一个工作簿
        HSSFWorkbook workbook = new HSSFWorkbook();
        //创建一个工作表
        HSSFSheet sheet = workbook.createSheet("供应商表");
        sheet.setDefaultRowHeightInPoints(16);//设置默认宽高
        // 第四步，创建单元格，并设置值表头 设置表头居中
        HSSFCellStyle styleTitle = workbook.createCellStyle();
        styleTitle.setAlignment(HorizontalAlignment.CENTER); // 创建一个居中格式
        styleTitle.setVerticalAlignment(VerticalAlignment.CENTER);//垂直居中
        HSSFFont fontTitle = workbook.createFont();
        fontTitle.setBold(true);
        fontTitle.setFontHeightInPoints((short) 11);
        styleTitle.setFont(fontTitle);
        //设置表头
        HSSFRow rowHead = sheet.createRow(0);
        //创建单元格
        String[] heads = {"供应商编码","供应商名称","地址","联系人","联系电话","入驻时间"};
        //设置每个单元格的宽
        int[] cellWidth = {256 * 15 + 184,256 * 20 + 184,256 * 50 + 184,256 * 20 + 184,256 * 20 + 184,256 * 22 + 184};
        for (int i = 0; i < heads.length; i++) {
            //创建单元格
            HSSFCell cellHead = rowHead.createCell(i);
            cellHead.setCellValue(heads[i]);
            cellHead.setCellStyle(styleTitle);
            //设置单元格的宽
            sheet.setColumnWidth(i, cellWidth[i]);
        }
        Example example = new Example(GoodsSupplier.class);
        String supplierName = goodsSupplier.getSupplierName();
        if (supplierName != null && !supplierName.isEmpty()) {
            example.createCriteria().andLike("supplierName","%" + supplierName + "%");
        }
        //查询出所有的数据
        List<GoodsSupplier> list = goodsSupplierMapper.selectByExample(example);
        if (list.size() > 0) {
            HSSFCellStyle styleContent = workbook.createCellStyle();
            styleContent.setAlignment(HorizontalAlignment.CENTER); // 创建一个居中格式
            styleContent.setVerticalAlignment(VerticalAlignment.CENTER); // 创建一个垂直居中
            //创建字体,设置字体样式
            HSSFFont fontContent = workbook.createFont();
            fontContent.setFontHeightInPoints((short) 11);
            styleContent.setFont(fontContent);
            final DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            int i =1;
            for (GoodsSupplier gs : list) {
                //写出数据到excel表
                //创建行
                HSSFRow row = sheet.createRow(i);
                row.setRowStyle(styleContent);
                //设置单元格的数据
                HSSFCell cell1 = row.createCell(0);
                cell1.setCellValue(gs.getId());
                cell1.setCellStyle(styleContent);
                HSSFCell cell2 = row.createCell(1);
                cell2.setCellValue(gs.getSupplierName());
                cell2.setCellStyle(styleContent);
                HSSFCell cell3= row.createCell(2);
                cell3.setCellValue(gs.getAddress());
                cell3.setCellStyle(styleContent);
                HSSFCell cell4= row.createCell(3);
                cell4.setCellValue(gs.getLinkman());
                cell4.setCellStyle(styleContent);
                HSSFCell cell5 = row.createCell(4);
                cell5.setCellValue(gs.getTelephone());
                cell5.setCellStyle(styleContent);

                //先创建出单元格
                HSSFCell cell6 = row.createCell(5);
                //先设置样式,在赋值
                cell6.setCellValue(df.format(gs.getCreateDate()));
                cell6.setCellStyle(styleContent);
                i ++;
            }
            ServletOutputStream os = response.getOutputStream();
            try {
                workbook.write(os);
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                //释放资源
                try {
                    os.close();
                    //关闭工作簿
                    workbook.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
